package com.demo.service.impl;

import com.demo.dao.SaticScheduleDao;
import com.demo.entity.SupTaskVideo;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description: 七牛
 * 文档
 * https://developer.qiniu.com/kodo/1239/java#rs-delete
 */
@Component
@Slf4j
public class OSSSingleUtil {

    @Value("${oss.accessKey}")
    private String accessKey;
    @Value("${oss.secretKey}")
    private String secretKey;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.urlPrefix}")
    private String urlPrefix;
    @Value("${downLoadPath}")
    private String downLoadPath;
    @Autowired
    private SaticScheduleDao saticScheduleDao;


    public void executeAll() throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                log.info("key=" + item.key);//文件名
//                log.info("hash=" + item.hash);
//                log.info("fsize=" + item.fsize);
//                log.info("mimeType=" + item.mimeType);
//                log.info("putTime=" + item.putTime);
//                log.info("endUser=" + item.endUser);
                //下载
                if (item.mimeType.equals("video/mp4")) {
                    String url = urlPrefix + item.key;
                    log.info(url);
                    downLoadFromUrl(url, item.key, downLoadPath, "abc");
                }
                //删除文件
                try {
                    log.info("删除");
                    bucketManager.delete(bucket, item.key);
                } catch (QiniuException ex) {
                    //如果遇到异常，说明删除失败
                    System.err.println(ex.code());
                    System.err.println(ex.response.toString());
                }
            }
        }
    }

    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public void downLoadFromUrl(String urlStr, String fileName, String savePath, String toekn) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        conn.setRequestProperty("lfwywxqyh_token", toekn);

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        log.info("info:" + url + " download success");

        // 插入数据
        SupTaskVideo supTaskVideo = new SupTaskVideo();
        supTaskVideo.setVideoName(fileName);
        supTaskVideo.setVideoPath(savePath);
        if (!StringUtils.isNullOrEmpty(fileName)){
            supTaskVideo.setSid(fileName.substring(0,fileName.indexOf("_")));
        }
        saticScheduleDao.insert(supTaskVideo);
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void main(String[] args) throws IOException {
        new OSSSingleUtil().executeAll();
    }
}
